package org.example;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.io.FileUtils;
import org.apache.poi.util.StringUtil;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class MainFrame extends JFrame {

    //控件
    private JLabel uploadLebal;
    private JButton FileSelectBtn;
    private JButton CodeGeneratorBtn;

    private JButton openResourceDialogBtn;
    private JTextField uploadPathTextField;
    private JPanel topPanel;
    private JPanel centerPanel;
    private JPanel bottomPanel;
    private JTextArea logTextArea;
    private String exportPath;
    private JLabel errorLevelLabel;
    private JComboBox<Integer> errorLeveComobox;
    private JLabel qrSize;
    private JTextField qrSizeText;

    public MainFrame() {

        //主窗口
        setTitle("二维码工具V1.0");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(750, 600);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        //上中下三个面板
        topPanel = new JPanel();
        centerPanel = new JPanel();
        bottomPanel = new JPanel();

        //顶部面板布局
        FlowLayout topFlowLayout = new FlowLayout(FlowLayout.LEFT);
        topPanel.setPreferredSize(new Dimension(0, 75));
//        topPanel.setBackground(Color.orange);
        topPanel.setLayout(topFlowLayout);

        //底部面板布局
        FlowLayout bottomFlowLayout = new FlowLayout();
        bottomFlowLayout.setAlignment(FlowLayout.RIGHT);
        bottomPanel.setLayout(bottomFlowLayout);

        //添加面板至容器
        add(topPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);


        uploadLebal = new JLabel("文件路径：");
        FileSelectBtn = new JButton("选择文件");

        openResourceDialogBtn = new JButton("打开生成文件夹");

        uploadPathTextField = new JTextField();
        CodeGeneratorBtn = new JButton("生成二维码");

        uploadPathTextField.setPreferredSize(new Dimension(300, 30));
        uploadPathTextField.setEditable(false);


        errorLevelLabel = new JLabel("二维码纠错级别：");
        Integer[] errorKey = {1, 2, 3, 4};
        errorLeveComobox = new JComboBox<Integer>(errorKey);
        errorLeveComobox.setPreferredSize(new Dimension(80, 30));


        qrSize = new JLabel("二维码尺寸(数字)");
        qrSizeText = new JTextField();
        qrSizeText.setText("100");
        qrSizeText.setPreferredSize(new Dimension(100, 30));

        topPanel.add(uploadLebal);
        topPanel.add(uploadPathTextField);
        topPanel.add(FileSelectBtn);
        topPanel.add(CodeGeneratorBtn);
        topPanel.add(openResourceDialogBtn);

        topPanel.add(errorLevelLabel);
        topPanel.add(errorLeveComobox);

        topPanel.add(qrSize);
        topPanel.add(qrSizeText);

        logTextArea = new JTextArea();
        logTextArea.setEditable(false);
        logTextArea.setMargin(new Insets(10, 10, 10, 10));
        centerPanel.add(logTextArea, BorderLayout.CENTER);


        //滚动条
        JScrollPane jsp = new JScrollPane(logTextArea);
        jsp.setSize(600, 400);
        add(jsp);

        //bottomPanel
        JLabel author = new JLabel("Author : lee@pengpaishuzi.com");
        bottomPanel.add(author);

        //按钮事件
        FileSelectBtn.addActionListener(e -> selectFile());

        CodeGeneratorBtn.addActionListener(e -> generator(uploadPathTextField.getText(), Integer.parseInt(errorLeveComobox.getSelectedItem().toString()), exportPath + File.separator + "img" + File.separator, Integer.parseInt(qrSizeText.getText()), Integer.parseInt(qrSizeText.getText())));

        openResourceDialogBtn.addActionListener(e -> {
            openResource();
        });

    }

    public void openResource() {
        if (StringUtil.isNotBlank(exportPath)) {
            try {
                Desktop.getDesktop().open(new File(exportPath + File.separator + "img"));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else {
            JOptionPane.showMessageDialog(this, "路径错误！", "路径类型错误！", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void selectFile() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.addChoosableFileFilter(new FileExtNameFilter("xlsx"));
        fileChooser.addChoosableFileFilter(new FileExtNameFilter("xls"));
//        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int option = fileChooser.showOpenDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            uploadPathTextField.setText(file.getAbsolutePath());
            exportPath = file.getParent();
        }
    }

    public void generator(String uploadPath, int errorLevel, String exportPath, int height, int width) {

        if (StringUtil.isBlank(uploadPath) || !(StringUtil.endsWithIgnoreCase(uploadPath, ".xlsx") || StringUtil.endsWithIgnoreCase(uploadPath, ".xls"))) {
            JOptionPane.showMessageDialog(this, "请选择Excel文件！", "文件类型错误！", JOptionPane.ERROR_MESSAGE);
            uploadPathTextField.setText("");
            return;
        }

        //读取文件
        ExcelReader reader = ExcelUtil.getReader(uploadPath);
        List<CardInfo> all = reader.readAll(CardInfo.class);

        logTextArea.setText("");

        logTextArea.append("二维码生成参数信息：\r\n");

        logTextArea.append("二维码纠错级别：" + errorLevel + "级别。\r\n");

        logTextArea.append("二维码尺寸大小：" + height + "*" + width + " 。\r\n");

        logTextArea.append("生成二维码数量：" + all.size() + "\r\n");

        logTextArea.append("开始生成...\r\n");

        //生成二维码
        QrConfig config = new QrConfig();
        config.setHeight(height);
        config.setWidth(width);
        // 高纠错级别
        config.setErrorCorrection(ErrorCorrectionLevel.forBits(errorLevel));

        //清空文件夹
        File exportFile = new File(exportPath);
        if (!exportFile.exists()) {
            exportFile.mkdirs();
        }
        try {
            FileUtils.cleanDirectory(exportFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        for (int i = 0; i < all.size(); i++) {
            QrCodeUtil.generate(all.get(i).getUrl().trim(), config, FileUtil.file(exportPath + all.get(i).getNum() + ".jpg"));
            logTextArea.append("生成第：" + (i + 1) + " 张:url=" + all.get(i).getUrl() + "\r\n");
            System.out.println("生成第：" + (i + 1) + " 张:url=" + all.get(i).getUrl());
        }
        logTextArea.append("二维码生成完成！\r\n");
        logTextArea.append("生成路径：" + exportPath);
    }

}
